'use strict';
const db = uniCloud.database()
const apis = db.collection('lj-apis')
const isJson = (argData) => {
	try {
		if (typeof JSON.parse(argData || '') === 'object') {
			return true
		}
	} catch (e) {}
	return false
}
exports.main = async (event, context) => {
	//event为客户端上传的参数
	// console.log('event : ', event,context)
	switch (event.httpMethod) {
		case "POST":
			if (!isJson(event.body)) {
				event.body = '{"' +
					decodeURIComponent(event.body)
					.replace(/"/g, '\\"')
					.replace(/&/g, '","')
					.replace(/=/g, '":"') +
					'"}'
			}
			event = JSON.parse(event.body)
			break
		case "GET":
			event = event.queryStringParameters
			break
	}
	if (!event.key) {
		event.msg = "参数key不能为空！"
		return event
	}
	if (!event.path) {
		event.msg = "参数path不能为空！"
		return event
	} else {
		event.path = event.key + event.path
	}
	switch (event.type) {
		case 'get':
			let getRes = await apis.where({
				path: event.path
			}).get()
			if (getRes.data[0] && isJson(getRes.data[0].data)) {
				getRes = JSON.parse(getRes.data[0].data)
			}
			if (isJson(event.data)) {
				event.data = JSON.parse(event.data)
			}
			if (typeof event.data === "object" && typeof getRes === "object") {
				Object.assign(getRes, event.data)
			}
			return getRes
		case 'update':
			// todo
			return true
		case 'del':
			const delRes = await apis.where({
				path: event.path
			}).remove()
			return delRes
		default:
			if (!isJson(event.data)) {
				event.data = JSON.stringify(event.data)
			}
			const addRes = await apis.add(event)
			//返回数据给客户端
			return addRes
	}
};
